package com.atguigu.gulimall.member.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayUserInfoShareRequest;
import com.alipay.api.response.AlipayUserInfoShareResponse;
import com.atguigu.common.utils.HttpUtils;
import com.atguigu.common.utils.ResourcesUtil;
import com.atguigu.gulimall.member.dao.MemberLevelDao;
import com.atguigu.gulimall.member.entity.MemberLevelEntity;
import com.atguigu.gulimall.member.exception.PhoneExistException;
import com.atguigu.gulimall.member.exception.UsernameExistException;
import com.atguigu.gulimall.member.vo.MemberLoginVo;
import com.atguigu.gulimall.member.vo.MemberRegistVo;
import com.atguigu.gulimall.member.vo.SocialUser;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.atguigu.common.utils.PageUtils;
import com.atguigu.common.utils.Query;

import com.atguigu.gulimall.member.dao.MemberDao;
import com.atguigu.gulimall.member.entity.MemberEntity;
import com.atguigu.gulimall.member.service.MemberService;


@Service("memberService")
public class MemberServiceImpl extends ServiceImpl<MemberDao, MemberEntity> implements MemberService {

    @Autowired
    private MemberLevelDao memberLevelDao;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<MemberEntity> page = this.page(
                new Query<MemberEntity>().getPage(params),
                new QueryWrapper<MemberEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public void regist(MemberRegistVo vo) {

        MemberDao memberDao = this.baseMapper;
        MemberEntity entity = new MemberEntity();
        // 设置默认等级
        MemberLevelEntity levelEntity = this.memberLevelDao.getDefaultLevel();

        entity.setLevelId(levelEntity.getId());
        // 检查用户名和手机号是否唯一    为了让controller感知异常，使用异常机制
        this.checkPhoneUnique(vo.getPhone());
        this.checkUsernameUnique(vo.getUserName());

        entity.setMobile(vo.getPhone());
        entity.setUsername(vo.getUserName());

        entity.setNickname(vo.getUserName());
        // 密码要进行加密存储
        BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
        String encode = passwordEncoder.encode(vo.getPassword());
        entity.setPassword(encode);
        // 其他的默认信息
        // ...
        // 保存
        memberDao.insert(entity);
    }

    @Override
    public void checkPhoneUnique(String phone) throws PhoneExistException {

        MemberDao memberDao = this.baseMapper;
        Integer mobile = memberDao.selectCount(new QueryWrapper<MemberEntity>().eq("mobile", phone));
        if (mobile > 0) {
            throw new PhoneExistException();
        }
    }

    @Override
    public void checkUsernameUnique(String username) throws UsernameExistException {

        MemberDao memberDao = this.baseMapper;
        Integer count = memberDao.selectCount(new QueryWrapper<MemberEntity>().eq("username", username));
        if (count > 0) {
            throw new UsernameExistException();
        }
    }

    @Override
    public MemberEntity login(MemberLoginVo vo) {

        String loginAccount = vo.getLoginAccount();
        String password = vo.getPassword();
        // 1、去数据库查询     SELECT * FROM ums_member WHERE username=? OR mobile=?
        MemberDao memberDao = this.baseMapper;
        MemberEntity entity = memberDao.selectOne(new QueryWrapper<MemberEntity>().eq("username", loginAccount)
                .or().eq("mobile", loginAccount));

        if (entity == null) {
            // 登录失败
            return null;
        } else {
            // 1、获取到数据库存放的password
            String passwordDB = entity.getPassword();

            BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
            // 2、密码匹配
            boolean matches = passwordEncoder.matches(password, passwordDB);
            if (matches) {
                return entity;
            } else {
                return null;
            }
        }
    }

    @Override
    public MemberEntity login(SocialUser socialUser) throws Exception {
        // 这个方法具有登录和注册的合并逻辑
        String uid = socialUser.getUid();
        // 1、判断当前社交用户是否已经登录过系统，也就是是否曾经注册过
        MemberDao memberDao = this.baseMapper;
        MemberEntity memberEntity = memberDao.selectOne(new QueryWrapper<MemberEntity>().eq("social_uid", uid));
        if (memberEntity != null) {
            // 说明这个用户已经注册过
            MemberEntity update = new MemberEntity();
            update.setId(memberEntity.getId());
            update.setAccessToken(socialUser.getAccess_token());
            update.setExpiresIn(socialUser.getExpires_in());

            memberDao.updateById(update);

            memberEntity.setAccessToken(socialUser.getAccess_token());
            memberEntity.setExpiresIn(socialUser.getExpires_in());

            return memberEntity;
        } else {
            // 2、没有查到当前社交用户对应的记录，就需要注册一个
            MemberEntity regist = new MemberEntity();
            String toolType = socialUser.getToolType();
            try {
                // 3、查询当前社交用户的社交账号信息（昵称，性别等）
                if ("微博".equals(toolType)) {
                    Map<String, String> map = new HashMap<>();
                    map.put("access_token", socialUser.getAccess_token());
                    map.put("uid", socialUser.getUid());

                    HttpResponse response = HttpUtils.doGet("https://api.weibo.com", "/2/users/show.json", "get", new HashMap<String, String>(), map);
                    if (response.getStatusLine().getStatusCode() == 200) {
                        // 查询成功
                        String json = EntityUtils.toString(response.getEntity());
                        JSONObject jsonObject = JSON.parseObject(json);
                        // 获取昵称
                        String name = jsonObject.getString("name");
                        // 获取性别
                        String gender = jsonObject.getString("gender");
                        // 注册
                        regist.setNickname(name);
                        regist.setGender("m".equals(gender) ? 1 : 0);
                    }
                }

                if ("支付宝".equals(toolType)) {
                    ResourcesUtil resourcesUtil = new ResourcesUtil("application.properties");
                    //在支付宝创建的应用的id
                    // String app_id = "2016102600765903";
                    String app_id = resourcesUtil.getValue("alipay.app_id");

                    // 商户私钥，您的PKCS8格式RSA2私钥
                    String merchant_private_key = resourcesUtil.getValue("alipay.merchant_private_key");

                    // 支付宝公钥,查看地址：https://openhome.alipay.com/platform/keyManage.htm 对应APPID下的支付宝公钥。
                    String alipay_public_key = resourcesUtil.getValue("alipay.alipay_public_key");
                    // 服务器[异步通知]页面路径  需http://格式的完整路径，不能加?id=123这类自定义参数，必须外网可以正常访问
                    // 支付宝会悄悄的给我们发送一个请求，告诉我们支付成功的信息
                    String notify_url = resourcesUtil.getValue("alipay.notify_url");

                    // 页面跳转同步通知页面路径 需http://格式的完整路径，不能加?id=123这类自定义参数，必须外网可以正常访问
                    //同步通知，支付成功，一般跳转到成功页
                    String return_url = resourcesUtil.getValue("alipay.return_url");

                    // 签名方式
                    String sign_type = resourcesUtil.getValue("alipay.sign_type");

                    // 字符编码格式
                    String charset = resourcesUtil.getValue("alipay.charset");

                    String timeout = "30m";

                    // 支付宝网关； https://openapi.alipaydev.com/gateway.do
                    String gatewayUrl = resourcesUtil.getValue("alipay.gatewayUrl");

                    AlipayClient alipayClient = new DefaultAlipayClient(gatewayUrl, app_id, merchant_private_key, "json",
                                                                        charset, alipay_public_key, sign_type);

                    AlipayUserInfoShareRequest request = new AlipayUserInfoShareRequest();
                    String auth_token = socialUser.getAccess_token();

                    AlipayUserInfoShareResponse userinfoShareResponse = alipayClient.execute(request, auth_token);
                    if (userinfoShareResponse.getBody() != null) {
                        String body = userinfoShareResponse.getBody();
                        String nickName = userinfoShareResponse.getNickName();
                        String gender = userinfoShareResponse.getGender();
                        String userName = userinfoShareResponse.getUserName();
                        // 注册
                        regist.setNickname(userName);
                        regist.setGender("m".equals(gender) ? 1 : 0);
                    }
                }
            } catch (Exception e) {
                log.error("查询当前社交用户的社交账号信息----报错");
                log.error(e.getMessage());
                throw new RuntimeException(e);
            }

            regist.setSocialUid(socialUser.getUid());
            regist.setAccessToken(socialUser.getAccess_token());
            regist.setExpiresIn(socialUser.getExpires_in());

            memberDao.insert(regist);

            return regist;
        }
    }

}